/**
 * Created by 断崖 on 2017/2/10.
 */
function observer(data) {
    if (!data || typeof data !== 'object') {
        return;
    }
    return new Observer(data);
}

function Observer(data) {
    this.data = data;
    this.walk();
}

Observer.prototype = {
    walk: function () {
        var self = this;
        Object.keys(this.data).forEach(function (key) {
            self.defineReactive(self.data, key, self.data[key]);
        })
    },
    defineReactive: function (data, key, value) {
        // 建立依赖
        var dep = new Dep();
        observer(value);

        Object.defineProperty(data, key, {
            enumerable: true,
            configurable: false,
            get: function () {
                if(Dep.target){
                    dep.depend();
                }
                return value;
            },
            set: function (newVal) {
                if (newVal === value) return;
                value = newVal;
                observer(newVal);
                // 通知依赖
                dep.notify();
            }
        })
    }
};

var uid = 0;
function Dep() {
    this.id = uid++;
    this.subs = [];
}

Dep.prototype = {
    addSub: function (sub) {
        this.subs.push(sub);
    },
    depend: function () {
        Dep.target.addDep(this);
    },
    notify: function () {
        this.subs.forEach(function (sub) {
            sub.update();
        })
    }
};